﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization;
using System.Web;
using System.Xml.Linq;

namespace Dnf.Tools.Sugar
{
    public class BitlyApi
    {
        private static readonly string apiKey = ConfigurationManager.AppSettings["bitlyApiKey"];
        private static readonly string login = ConfigurationManager.AppSettings["bitlyLogin"];

        public static BitlyResults ShortenUrl(string longUrl)
        {
            var url =
                string.Format("http://api.bit.ly/shorten?format=xml&version=2.0.1&longUrl={0}&login={1}&apiKey={2}",
                              HttpUtility.UrlEncode(longUrl), login, apiKey);
            var resultXml = XDocument.Load(url);
            var x = (from result in resultXml.Descendants("nodeKeyVal")
                     select new BitlyResults
                                {
                                    UserHash = result.Element("userHash").Value,
                                    ShortUrl = result.Element("shortUrl").Value
                                }
                    );
            return x.Single();
        }
    }

    public class BitlyResults
    {
        public string UserHash { get; set; }

        public string ShortUrl { get; set; }
    }
}